<?php

/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */
class importexport_tasks_runqifa3import extends base_task_abstract implements base_interface_task
{

    const TTL = 86400;//缓存时间
    const REDIS_DB = 1;
    public  $db;

    public function exec($params = null)
    {
        set_time_limit(3600);
        $this->db = kernel::database();
        $taskModel = app::get('importexport')->model('task');
        $taskModel->update(array('status' => 4), array('key' => $params['key']));//执行队列，更新队列状态

        $redis = kernel::single('base_kvstore_redis2');
        $redis->selects(self::REDIS_DB);


        $objGoods = kernel::single('b2c_mdl_goods');
        $objProduct = kernel::single('b2c_mdl_products');
        $count = $redis->lLen($params['key']);
        $message = '';
        for ($i = 0; $i < $count; $i++) {
            $rowsdata = $redis->rpop($params['key']);
            $rows = unserialize($rowsdata);
            $msg = null;

            $product = $objProduct->getProductByBn($rows[0]);

            $goods_id = intval($product[0]['goods_id']);
            if($goods_id <= 0){
                $message = 'bn为'.$rows[0].'的商品不存在'.chr(13).chr(10).$message;
            }else {
                if($rows[1] == 0){
                    $finderResult['goods_id'][] = $goods_id;
                }else{
                    $finderResultShelve['goods_id'][] = $goods_id;
                }

                $this->db->exec("UPDATE `sdb_b2c_goods` SET `store` = '{$rows[1]}' WHERE `sdb_b2c_goods`.`goods_id` = {$goods_id}");
                $this->db->exec("UPDATE `sdb_b2c_products` SET `store` = '{$rows[1]}' WHERE `sdb_b2c_products`.`goods_id` = {$goods_id}");

                $redis->lPush($params['key'] . '_complate', serialize($rows));
                $redis->expire($params['key'] . '_complate', self::TTL);
            }
        }

        $rs = $objGoods->setEnabled($finderResult,'false',$message);
        $rss = $objGoods->setEnabled($finderResultShelve,'true',$message);
        if ($message) {
            if ($redis->lLen($params['key'] . '_complate')) {
                $params['status'] = $params['status'] = 8;
            } else {
                $params['status'] = $params['status'] = 6;
            }
        } else {
            $params['status'] = $params['status'] = 5;
        }
        if ($message) {
            $redis->set($params['key'] . '_error_message', $message);
        }

        $msg = '共' . $count . '条,' . '完成' . $redis->lLen($params['key'] . '_complate') . '条';
        $taskModel->update(array('status' => $params['status'], 'complete_date' => time(), 'message' => $msg), array('key' => $params['key']));
    }

}
